<?php
/**
 * Created by PhpStorm.
 * 账户相关操作 需校对登录状态
 * User: 王金鑫
 * Date: 2018/8/23
 * Time: 16:02
 */
namespace app\facescore\home;
use app\common\controller\Common;
use think\Db;
use app\common\model\AdminAnnex as AnnexModel;

class Account extends Common
{
    /**
     * 发布内容
     * @return \think\response\Json
     */
    public function send(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $data = [
            'uid' => input('uid'),
            'describe' => input('describe'),
            'rmb_reward_single' => input('rmb_reward_single'),
            'mag_reward_single' => input('mag_reward_single'),
            'rmb_reward_all' => input('rmb_reward_all'),
            'mag_reward_all' => input('mag_reward_all'),
            'create_time' => date("Y-m-d H:i:s"),
            'formId' => input('formId')
        ];
        Db::name('facescore_content')->insert($data);
        return json(['content_id' => Db::name('facescore_content')->getLastInsID()]);
    }
    /**
     * 附件上传
     * @param string $from 来源
     * @param string $group 附件分组,默认sys[系统]，模块格式：m_模块名，插件：p_插件名
     * @param string $water 水印，参数为空默认调用系统配置，no直接关闭水印，image 图片水印，text文字水印
     * @param string $thumb 缩略图，参数为空默认调用系统配置，no直接关闭缩略图，如需生成 500x500 的缩略图，则 500x500多个规格请用";"隔开
     * @param string $thumb_type 缩略图方式
     * @param string $input 文件表单字段名
     * @author 橘子俊 <364666827@qq.com>
     * @return json
     */
    public function upload(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
       $res = AnnexModel::upload('小程序', 'm_facescore', 'image', '500*500',config('upload.thumb_type'), 'sendImg');
       if($res['code'] == 1) {
           $data = [
               'pic_path' => $res['data']['file'],
               'type' => input('type'),
               'content_id' => input('content_id')
           ];
           Db::name('facescore_imgs')->insert($data);
       }
    }

    /**
     * 申请上首页
     * @return \think\response\Json
     */
    public function shenqing(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        Db::name('facescore_content')->where(['id' => input('content_id')])->update(['is_apply' => 1]);
        return json(['msg' => 'success']);
    }

    /**
     * 修改个人信息
     */
    public function editAccount(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $userData = [
            'nick' => input('nick'),
            'username' => input('nick'),
            'qianming' => input('qianming'),
            'sex' => input('sex'),
            'birthday' => input('birthday')
        ];
        Db::name('admin_member')->where(['openid' => input('openid')])->update($userData);
        return json(['msg' => 'success']);
    }

    /**
     * 我收到的赞赏列表
     */
    public function my_reward_get(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        //先循环出所有作品
        $data_list = Db::name('facescore_content c')->join('facescore_reward r','r.content_id = c.id')->where(['c.uid' => input('uid'),'r.status' => 1])->field('c.id content_id,c.is_del,r.*')->order('r.id desc')->paginate(10, false, ['query' => input('get.')])->toArray();

        foreach ($data_list['data'] as $key => $value) {
            //用户昵称
            $data_list['data'][$key]['nick'] = userInfo($data_list['data'][$key]['uid'],'nick');
            //微信头像
            $data_list['data'][$key]['avatar'] = userInfo($data_list['data'][$key]['uid'],'avatar');
            //图集列表
            $data_list['data'][$key]['imgs'] = content_imgs($data_list['data'][$key]['content_id']);
        }
        return json($data_list);
    }

    /**
     * 我发出的赞赏
     */
    public function  my_reward_set(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $data_list = Db::name('facescore_reward r')->join('facescore_content c','c.id = r.content_id')->where(['r.uid' => input('uid'),'r.status' => 1])->field('c.*')->order('r.id desc')->paginate(5, false, ['query' => input('get.')])->toArray();
        foreach ($data_list['data'] as $key => $value) {
            //用户昵称
            $data_list['data'][$key]['nick'] = userInfo($data_list['data'][$key]['uid'],'nick');
            //微信头像
            $data_list['data'][$key]['avatar'] = userInfo($data_list['data'][$key]['uid'],'avatar');
            //图集列表
            $data_list['data'][$key]['imgs'] = content_imgs($data_list['data'][$key]['id']);
            //图集处理
            if(input('uid') != null) {
                if(!checkLogin()){
                    return json(['msg' => '没有登录']);
                }
                $data_list['data'][$key]['imgs'] = deal_imgs(input('uid'), $data_list['data'][$key]['imgs'],$data_list['data'][$key]['id']);
            }
            //发布时间
            $data_list['data'][$key]['send_time'] = $this->format_date($data_list['data'][$key]['create_time']);
            //打赏人数
            $data_list['data'][$key]['reward_person_count'] = $this->reward_person_count($data_list['data'][$key]['id']);
        }
        return json($data_list);
    }

    /**
     * 时间格式转换成 xx 天/月等 前
     * @param $time
     * @return string
     */
    function format_date($time){
        $time = strtotime($time);
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }

    /**
     * 打赏总人数
     * @param $content_id
     * @return int|string
     */
    function reward_person_count($content_id){
        $res = Db::name('facescore_reward')->where(['content_id' => $content_id,'status' => 1])->count("distinct uid");
        return $res;
    }

    /**
     * 删除图集
     */
    function delete_content(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        Db::name('facescore_content')->where(['id' => input('content_id')])->update(['is_del' => 1]);
        return json(['code' => 1]);
    }

    /**
     * 获取小程序码
     * @param $goodId
     * @return string
     */
    public function getQrcode($content_id = '') {
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $access_token = AccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacode?" . 'access_token=' . $access_token;//wx.qrurl为请求小程序二维码的网址
        $path = "pages/look/index?content_id=".$content_id."&type=1";//扫码后进入的页面路径以及携带的参数
        $width = 430;//宽度
        $data = [
            "path" => $path,
            "width" => $width,
            "is_hyaline" => true
        ];
        $data = json_encode($data);
        $return = send_post($url, $data);
        //将生成的小程序码存入相应文件夹下
        file_put_contents('./upload/qrcode/' . $content_id . '.png', $return);
        return '生成小程序码成功';
    }


    //麦粒账户相关操作

    /**
     * 获取麦粒 充值地址
     */
    public function getMagAddress(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $data = [
            "tokenSymbol" => 'MAG',
            "userCode" => input('mobile')
        ];
        $data = json_encode($data);
        $res = send_post(config('module_facescore.mag_api_url') . '/asset/rechargeAddress/MAG/'.input('mobile'),$data,'GET');
        return $res;
    }

    /**
     * 获取麦粒账户余额
     */
    public function getMagBalance(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $res = send_post(config('module_facescore.mag_api_url') . '/asset/detail/MAG/'.input('mobile'),'','GET');


        return $res;
    }

    //测试向卖颜值官方转账
    // public function test(){
    //       $txNo = 'facescore_rewardToOfficial_'.date('ymdHis').'_toOffical';
    //             $post_data = [
    //                 "txNo" => $txNo,
    //                 "fromUserCode" => '18841692393',
    //                 "toUserCode" => 'facescoreOfficial',  //麦颜值官方收款账户 标识
    //                 "amt" => 2000,  //计算方式为 打赏者打赏金额 - 被打赏者收入金额
    //                 "describe" => '向卖颜值官方账户转账一次',
    //                 "message" => ''
    //             ];
    //             $res = http_request(config('module_facescore.mag_api_url') . '/payment/transfer/MAG',$post_data);
    // }

    /**
     * 使用麦粒支付，打赏
     */
    public function magPay(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $order_id = input('order_id');
        //订单表相关字段
        $order = db::name('facescore_reward')->where("id",$order_id)->find();
        //被打赏人作品信息
        $bei_user =  db::name('facescore_content')->where("id",$order['content_id'])->find();
        if($order['status'] == 1) {
            return json(['msg' => '订单已支付成功','code' => 1]);
        }

        if((double)input('money') == (double)($order['money']) && $order['status'] == 0){
            //事务
            try{
                Db::startTrans();

                //mag转账操作

                $fromUserCode = userInfo($order['uid'],'mobile');   //支付方手机号
                $toUserCode = userInfo($bei_user['uid'],'mobile');  //收款方手机号
                $txNo = 'facescore_rewardToUser_'.date('ymdHis').'_'.$order_id;
                //被打赏人实际到账金额 = 订单金额 * 后台设置的费率
                $money = $order['money'] * config('module_facescore.mag_rate');



                //处理设置订单支付成功
                db::name('facescore_reward')->where('id',$order_id)->update(['status'=>'1']);

                //打赏人加一条流水记录
                $flow_data = [
                    'time' => date('Y-m-d H:i:s',time()),
                    'name' => config('module_facescore.dashangzhichu'),
                    'money' => 0 - (double)$order['money'],
                    'uid' => $order['uid'], //打赏人的uid
                    'type' => 'mag'
                ];

               db::name('facescore_flow')->insert(  $flow_data);


                //平台收入加一条流水记录
                $flow_data = [
                    'time' => date('Y-m-d H:i:s',time()),
                    'name' => '用户打赏平台收入',
                    'money' => (double)$order['money'] - (double)$money,
                    'uid' => 'facescoreOfficial', //打赏人的uid
                    'type' => 'mag'
                ];
                db::name('facescore_flow')->insert(  $flow_data);

                //被赏人加一条流水记录
                $flow_data = [
                    'time' => date('Y-m-d H:i:s',time()),
                    'name' => config('module_facescore.dashangshouru'),
                    'money' => $money,
                    'uid' => $bei_user['uid'], //打赏人的uid
                    'type' => 'mag'
                ];
                db::name('facescore_flow')->insert($flow_data);

                //向打赏人发送模板消息
                $openid = userInfo($bei_user['uid'],'openid');
                $formId = $bei_user['formId'];
                $rewardNick = userInfo($order['uid'],'nick'); //打赏人

                $access_token = AccessToken();

                if ($access_token) {
                    $templateData = $this->create_template($openid, $formId, $rewardNick,$order['money'],$rewardNick . "觉得你很赞，对你表示了支持哦"); //拼接模板数据

                    $res = send_post('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $access_token, $templateData);
//                    print_r($res);
                }
                 //提交事务
                Db::commit();
                $order = db::name('facescore_reward')->where("id",$order_id)->find();
                if($order['status'] == 1) {
                //对接转账接口 打赏者向被打赏者支付
                $post_data = [
                    "txNo" => $txNo,
                    "fromUserCode" => $fromUserCode,
                    "toUserCode" => $toUserCode,
                    "amt" => $money,
                    "describe" => '麦颜值打赏',
                    "message" => ''
                ];
                $res = http_request(config('module_facescore.mag_api_url') . '/payment/transfer/MAG',$post_data);
                $res = json_decode($res,true);
                if($res['status'] != '0000') {
                    throw new \think\exception\HttpException(404, '异常消息', null);
                }


                //对接转账接口 打赏者向平台支付
                $txNo = 'facescore_rewardToOfficial_'.date('ymdHis').'_'.$order_id;
                $post_data = [
                    "txNo" => $txNo,
                    "fromUserCode" => $fromUserCode,
                    "toUserCode" => 'facescoreOfficial',  //麦颜值官方收款账户 标识
                    "amt" => (double)$order['money'] - (double)$money,  //计算方式为 打赏者打赏金额 - 被打赏者收入金额
                    "describe" => '麦颜值打赏官方账户收取手续费',
                    "message" => ''
                ];
                $res = http_request(config('module_facescore.mag_api_url') . '/payment/transfer/MAG',$post_data);
                $res = json_decode($res,true);
                if($res['status'] != '0000') {
                    throw new \think\exception\HttpException(404, '异常消息', null);
                }
               }
            } catch (\Exception $e) {
                //回滚事务

                Db::rollback();
            } finally {
                $order = db::name('facescore_reward')->where("id",$order_id)->find();
                if($order['status'] == 1) {
                    return json(['code' => 1,'msg' => '支付成功']);
                }else{
                    return json(['code' => -1,'msg' => '支付失败']);
                }
            }
        }else{
            return json(['msg' => '支付金额有误','code' => -1]);
        }
    }

    //2.拼装模板，创建通知内容
    private function create_template($openId, $formId, $rewardNick,$money,$content) {
        $templateData['keyword1']['value'] = $rewardNick;
        $templateData['keyword1']['color'] = '#303030';
        $templateData['keyword2']['value'] = $money . 'MAG';
        $templateData['keyword2']['color'] = '#1aaba8';
        $templateData['keyword3']['value'] = strip_tags($content);
        $templateData['keyword3']['color'] = '#303030';
        $templateData['keyword4']['value'] = date('Y-m-d H:i:s');
        $templateData['keyword4']['color'] = '#303030';
        $data['touser'] = $openId;
        $data['template_id'] = config('module_facescore.template_id');
        $data['page'] = 'pages/my/record'; //用户点击模板消息后的跳转页面
        $data['form_id'] = $formId;
        $data['data'] = $templateData;
        return json_encode($data);
    }

    /**
     * 用户交易流水记录
     */
    public function flow(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $data_list = db::name('facescore_flow')->where(['uid' => input('uid')])->order('time desc')->paginate(10, false, ['query' => input('get.')])->toArray();
        return json($data_list);
    }

    /**
     * 用户提现
     * money 提现金额
     * address 地址
     * mobile 手机号
     */
    public function magTixian(){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        //没有接口写不了
        return json(['msg' => '敬请期待']);
    }

    /*
     * 修改用户头像啦
     */
    public function changeAvatar($uid = ''){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $res = AnnexModel::upload('小程序', 'm_facescore', 'no', '300*300', config('upload.thumb_type'), 'sendImg');
        if($res['code'] == 1) {
            Db::name('admin_member')->where(['id' => $uid])->update(['avatar' => config('base.site_domain').$res['data']['file']]);
        }
    }

    public function changeHomePageImg($uid = ''){
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $res = AnnexModel::upload('小程序', 'm_facescore', 'no', '300*300', config('upload.thumb_type'),'sendImg');
        if($res['code'] == 1) {
            Db::name('admin_member')->where(['id' => $uid])->update(['home_page_img' => config('base.site_domain').$res['data']['file']]);
        }
        return config('base.site_domain').$res['data']['file'];
    }

    //获得邀请的二维码
    public function getInviQrcode() {
        if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $access_token = AccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacode?" . 'access_token=' . $access_token;//wx.qrurl为请求小程序二维码的网址
        $path = "pages/inviation/login?invi_uid=".input('uid');//扫码后进入的页面路径以及携带的参数
        $width = 430;//宽度
        $data = [
            "path" => $path,
            "width" => $width,
            "is_hyaline" => true
        ];
        $data = json_encode($data);
        $return = send_post($url, $data);
        //将生成的小程序码存入相应文件夹下
        file_put_contents('./upload/inviqrcode/' . input('uid') . '.png', $return);
        return '生成小程序码成功';
    }

      //邀请登录时更新邀请人的uid
    function setInviUid(){
         if(!checkLogin()){
            return json(['msg' => '没有登录']);
        }
        $res = Db::name('admin_member')->where(['id' => input('uid')])->find();
        if($res['invi_uid'] == null) {
             Db::name('admin_member')->where(['id' => input('uid')])->update(['invi_uid' => input('invi_uid')]);
             return json(['code' => 1,'msg' => '更新邀请人uid成功']);
        }else{
            return json(['code' => -1,'msg' => '已经存在邀请人']);
        }
    }

    public function test(){
     
        $data = [
            "tokenSymbol" => 'MAG',
            "userCode" => 'facescoreOfficial',
            "pageNumber" => 1
        ];
         $data = json_encode($data);
        $res = send_post(config('module_facescore.mag_api_url') . '/asset/flow/MAG/facescoreOfficial',$data,'GET');
        return $res;
    }
}